package com.school.fuyuan.business.controller;

import com.school.fuyuan.business.model.po.User;
import com.school.fuyuan.business.model.vo.AddUserVo;
import com.school.fuyuan.business.model.vo.FollowUserOutVo;
import com.school.fuyuan.business.service.UserService;
import com.school.fuyuan.common.annotation.Authenticate;
import com.school.fuyuan.common.exception.CommonRuntimeException;
import com.school.fuyuan.common.message.RequestMsg;
import com.school.fuyuan.common.message.ResponseMsg;
import com.school.fuyuan.common.util.ParameterUtils;
import com.school.fuyuan.common.util.VerifyCode;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/12 22:18
 * @description
 */
@Controller
@RequestMapping("user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 修改用户密码
     *
     * @param requestMsg
     * @return
     */
    @PostMapping("updatePassword")
    @ResponseBody
    public ResponseMsg updatePassword(@RequestBody @Valid RequestMsg<Map<String, String>> requestMsg) {
        ResponseMsg responseMsg = new ResponseMsg();
        userService.updatePassword(requestMsg, responseMsg);
        return responseMsg;
    }

    /**
     * 修改用户角色
     *
     * @return
     */
    @PostMapping("/updateUserRole")
    @ResponseBody
    @Authenticate(openAuth = true, authItems = {"/info/user/getUsers"})
    public ResponseMsg updateUserRole(@RequestBody @Valid RequestMsg<Map<String, String>> requestMsg) {
        String roleId = requestMsg.getData().get("roleId");
        String userId = requestMsg.getData().get("userId");
        ParameterUtils.assertValue("roleId", roleId);
        ParameterUtils.assertValue("userId", userId);
        userService.updateUserRole(userId, roleId);
        ResponseMsg responseMsg = new ResponseMsg();
        return responseMsg;
    }


    /**
     * 添加用户
     *
     * @param requestMsg
     * @return
     */
    @PostMapping("addUser")
    @ResponseBody
    @Authenticate(openAuth = true, authItems = {"/info/user/addUser"})
    public ResponseMsg addUser(@RequestBody @Valid RequestMsg<AddUserVo> requestMsg) {
        AddUserVo addUserVo = requestMsg.getData();
        userService.addUser(addUserVo);
        ResponseMsg responseMsg = new ResponseMsg();
        return responseMsg;
    }

    @PostMapping("login")
    @ResponseBody
    public ResponseMsg<Map<String, Object>> login(@RequestBody @Valid RequestMsg<Map<String, String>> requestMsg, HttpSession session) {
        Map<String, String> map = requestMsg.getData();
        String reqCode = map.get("code");
        String code = String.valueOf(session.getAttribute("code"));
        ParameterUtils.assertValue("验证码", reqCode);
        if (!reqCode.equalsIgnoreCase(code)) {
            throw new CommonRuntimeException("-301", "验证码错误");
        }
        String password = map.get("password");
        String mobile = map.get("mobile");
        ParameterUtils.assertValue("手机号码", mobile);
        ParameterUtils.assertValue("password", password);
        Map<String, Object> map1 = userService.login(mobile, password);
//        userService.register(addUserVo);
        ResponseMsg<Map<String, Object>> responseMsg = new ResponseMsg();
        responseMsg.setData(map1);
        return responseMsg;
    }

    @RequestMapping("verifyCode")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        VerifyCode verifyCode = new VerifyCode();
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            verifyCode.output(verifyCode.createImage(), os);//输出图片方法
            String code = verifyCode.getText();
            session.setAttribute("code", code);
        } catch (Exception e) {
            throw new CommonRuntimeException("-809", "获取验证码异常" + e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                throw new CommonRuntimeException("-810", "IO异常" + e);
            }
        }
    }

    /**
     * 获取用户（跟进人）
     *
     * @return
     */
    @PostMapping("getFollowUsers")
    @ResponseBody
    public ResponseMsg<List<FollowUserOutVo>> getFollowUsers(@RequestBody @Valid RequestMsg requestMsg) {
        Map<String, Object> resultMap = userService.getFollowUsers(requestMsg);
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg.setData(resultMap);
        return responseMsg;
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @PostMapping("getUsers")
    @ResponseBody
    @Authenticate(openAuth = true, authItems = {"/info/user/getUsers"})
    public ResponseMsg<List<User>> getUsers(@RequestBody @Valid RequestMsg requestMsg) {
        Map<String, Object> resultMap = userService.getUsers(requestMsg);
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg.setData(resultMap);
        return responseMsg;
    }


    /**
     * 删除用户
     *
     * @return
     */
    @PostMapping("deleteUser")
    @ResponseBody
    @Authenticate(openAuth = true, authItems = {"/info/user/deleteUser"})
    public ResponseMsg<List<User>> deleteUser(@RequestBody @Valid RequestMsg<Map<String,Integer>> requestMsg) {
        Integer userId = requestMsg.getData().get("userId");
        if (ParameterUtils.isEmpty(userId)) {
            throw new CommonRuntimeException("-1", "请输入要删除的用户Id");
        }
        userService.deleteUser(userId);
        ResponseMsg responseMsg = new ResponseMsg();
        return responseMsg;
    }


}
